package com.cloudeasy.post.controller;

import com.cloudeasy.api.util.ResultUtil;
import com.cloudeasy.api.vo.Result;
import com.cloudeasy.api.vo.post.SimpleUserInfoVO;
import com.cloudeasy.api.vo.post.StoreyVO;
import com.cloudeasy.core.bean.JwtParser;
import com.cloudeasy.post.dto.ReviewDTO;
import com.cloudeasy.post.po.Storey;
import com.cloudeasy.post.service.StoreyService;
import com.cloudeasy.post.service.expand.SimpleUserInfoService;
import com.cloudeasy.post.util.StoreyUtil;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/storey")
public class StoreyController {
    private final StoreyService storeyService;

    private final SimpleUserInfoService simpleUserInfoService;

    private final JwtParser jwtParser;

    public StoreyController(StoreyService storeyService, SimpleUserInfoService simpleUserInfoService, JwtParser jwtParser) {
        this.storeyService = storeyService;
        this.simpleUserInfoService = simpleUserInfoService;
        this.jwtParser = jwtParser;
    }

    /**
     * 回复
     *
     * @param authentication {@link Authentication}
     * @param replyId        评论Id
     * @param reviewDTO      {@link ReviewDTO}
     * @return {@link Result<Boolean>}
     */
    @PostMapping("/{replyId}")
    public Result<Boolean> save(Authentication authentication,
                                @PathVariable("replyId") String replyId,
                                @RequestBody @Validated ReviewDTO reviewDTO) {
        String userId = (String) jwtParser.getOnBody(authentication, "userId");
        return ResultUtil.success(storeyService.save(replyId, userId, reviewDTO));
    }

    /**
     * 获取某条评论的所有回复
     *
     * @param replyId 评论Id
     * @return {@link List<StoreyVO>}的{@link Result}
     */
    @GetMapping("/{replyId}")
    public Result<List<StoreyVO>> save(@PathVariable("replyId") String replyId) {
        List<Storey> storeys = storeyService.listByReplyId(replyId);
        List<String> answererIds = storeys.stream().map(Storey::getAnswererId).distinct().collect(Collectors.toList());
        List<SimpleUserInfoVO> simpleUserInfoVOS = simpleUserInfoService.obtainSimpleUserInfo(answererIds);
        return ResultUtil.success(StoreyUtil.convert(storeys, simpleUserInfoVOS));
    }
}
